package com.example.service;

import com.example.common.RoleE;
import com.example.entity.Account;
import com.example.entity.Student;
import com.example.exception.CustomException;
import com.example.mapper.StudentMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentService {
    @Resource
    private StudentMapper studentMapper;

    public Account login(Account account){
        Student databStudent = studentMapper.selectByUsername(account.getUsername());
        if(databStudent == null){
            throw new CustomException("账号或密码错误");
        }
        if(!databStudent.getPassword().equals(account.getPassword())){
            throw new CustomException("账号或密码错误");
        }
        String token = TokenUtils.genToken(databStudent.getId().toString(),databStudent.getPassword());
        databStudent.setToken(token);
        return databStudent;
    }

    public void register(Account account) {
        Student student = new Student();
        student.setUsername(account.getUsername());
        student.setPassword(account.getPassword());
        student.setName("DEFAULT");
        this.insert(student);
    }

    public void insert(Student student) {
        Student dbStudent = studentMapper.selectByUsername(student.getUsername());
        if(dbStudent != null){
            throw new CustomException("账号已存在");
        }
        if(student.getSex()==null){
            student.setSex("男");
        }
        if(student.getName()==null){
            student.setName("学生");
        }
        student.setRole(RoleE.STUDENT.name());
        studentMapper.insert(student);
    }

    public void updateById(Student student) {
        studentMapper.updateById(student);
    }

    public void deleteById(Integer id) {
        studentMapper.deleteById(id);
    }


    public PageInfo<Student> selectPage(Integer pageNum,Integer pageSize,Student student){  //页码和页数
        PageHelper.startPage(pageNum,pageSize);
        List<Student> studentList=studentMapper.selectAll(student);
        return PageInfo.of(studentList);
    }

    public Account selectSingle(String username) {
        Account student = studentMapper.selectByUsername(username);
        return student;
    }
}
